package com.liugh.service.zhongche.Imp;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.liugh.entity.standard.Announcement;
import com.liugh.mapper.zhongche.AnnouncementMapper;
import com.liugh.model.DownloadModel;
import com.liugh.service.IUserService;
import com.liugh.service.zhongche.IAnnouncementService;
import com.liugh.service.zhongche.ISearchService;
import com.liugh.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**标准化公告 .
 * Created by Fatao on 2018/10/31 .
 */
@Service
public class AnnouncementServiceImpl implements IAnnouncementService {


    @Autowired
    AnnouncementMapper announcementMapper;

    @Autowired
    ISearchService searchService;


    @Autowired
    IUserService userService;

    /**
     * 添加标准化公告 .
     * @param announcement .
     * @return .
     */
    public Announcement addAnnouncement(Announcement announcement) {
        return CommonUtil.isDBOpSuccess(announcementMapper.insert(announcement)) ? announcement : null;
    }


    /**
     * 更新公告 .
     * @param announcement .
     * @return .
     */
    public Announcement updateAnnouncementById(Announcement announcement) {
        return CommonUtil.isDBOpSuccess(announcementMapper.updateById(announcement)) ? announcement : null;
    }

    /**
     * 删除公告 .
     * @param id .
     * @return .
     */
    public int delAnnouncementById(int id) {
        return announcementMapper.deleteById(id);
    }

    /**
     * 根据id获取公告 .
     * @param id .
     * @return .
     */
    public Announcement getAnnouncementById(int id) {
        return announcementMapper.selectById(id);
    }



    /**
     * 分页获取所有的公告 .
     * @param page .
     * @return .
     */
    public Page<Announcement> getAllAnnouncement(Page<Announcement> page) {
        List<Announcement> announcementList = announcementMapper.selectPage(page, new EntityWrapper<Announcement>().orderBy("create_time", false));
        for (Announcement announcement : announcementList) {
            announcement.setAuthorName(userService.getUserByUserNo(announcement.getAuthor()).getUsername());
        }
        page.setRecords(announcementList);
        return page;
    }

    /**
     * 下载附件时返回文件链接及原始文件名
     * @param id
     * @return
     */
    @Override
    public DownloadModel downloadAttachment(int id) {
        Announcement announcement = announcementMapper.selectById(id);
        String fileUrl = announcement.getAttachment();
        String filename = searchService.getOriginName(CommonUtil.getFileNameByUrl(fileUrl));
        if (!StrUtil.isEmpty(fileUrl) && !StrUtil.isEmpty(filename)) {
            return new DownloadModel(fileUrl, filename);
        }
        return null;
    }
}
